<template>
    <div class="add-pet-page">
        <van-nav-bar
            title="添加宠物"
            left-text="返回"
            left-arrow
            @click-left="handleBack"
        />
        
        <div class="page-content">
            <!-- 宠物头像上传 -->
            <div class="avatar-section">
                <div class="section-title">宠物头像</div>
                <div class="uploader-wrapper">
                    <van-uploader
                        v-model="fileList"
                        :max-count="1"
                        :after-read="afterRead"
                        :before-delete="beforeDelete"
                        upload-text="上传头像"
                    >
                        <template #default>
                            <div class="custom-upload-area">
                                <img 
                                    v-if="fileList.length === 0" 
                                    src="/QQ_1760608520183.png" 
                                    alt="默认头像"
                                    class="default-avatar"
                                />
                            </div>
                        </template>
                    </van-uploader>
                </div>
             
            </div>
            
            <!-- 表单区域 -->
            <van-form @submit="handleSubmit" class="pet-form">
                <!-- 宠物昵称 -->
                <van-field
                    v-model="form.pet_name"
                    name="pet_name"
                    label="宠物昵称"
                    placeholder="请输入宠物昵称"
                    :rules="[{ required: true, message: '请填写宠物昵称' }]"
                    class="form-item"
                />
                
                <!-- 宠物类型 -->
                <van-field name="pet_type" label="宠物类型" class="form-item no-border">
                    <template #input>
                        <van-radio-group 
                            v-model="form.pet_type" 
                            direction="horizontal"
                            class="pet-type-radio"
                        >
                            <van-radio name="猫猫" icon-size="18px">猫猫</van-radio>
                            <van-radio name="狗狗" icon-size="18px">狗狗</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>
                
                <!-- 宠物性别 -->
                <van-field
                    v-model="form.pet_gender"
                    readonly
                    name="pet_gender"
                    label="宠物性别"
                    placeholder="请选择宠物性别"
                    @click="showGenderPicker = true"
                    class="form-item"
                />
                
                <!-- 宠物毛色 -->
                <van-field
                    v-model="form.pet_color"
                    readonly
                    name="pet_color"
                    label="宠物毛色"
                    placeholder="请选择宠物毛色"
                    @click="showColorPicker = true"
                    class="form-item"
                />
                
                <!-- 宠物品种 -->
                <van-field
                    v-model="form.pet_breed"
                    readonly
                    name="pet_breed"
                    label="宠物品种"
                    placeholder="请选择宠物品种"
                    @click="showBreedPicker = true"
                    class="form-item"
                />
                
                <!-- 宠物年龄 -->
                <van-field
                    v-model="form.pet_age"
                    readonly
                    name="pet_age"
                    label="宠物年龄"
                    placeholder="请选择宠物年龄"
                    @click="showAgePicker = true"
                    class="form-item"
                />
                
                <!-- 提交按钮 -->
                <div class="submit-btn">
                    <van-button 
                        round 
                        block 
                        type="primary" 
                        native-type="submit"
                        :loading="loading"
                    >
                        添加宠物
                    </van-button>
                </div>
            </van-form>
        </div>
        
        <!-- 性别选择器 -->
        <van-popup v-model:show="showGenderPicker" position="bottom">
            <van-picker
                :columns="genderOptions"
                @confirm="onGenderConfirm"
                @cancel="showGenderPicker = false"
            />
        </van-popup>
        
        <!-- 毛色选择器 -->
        <van-popup v-model:show="showColorPicker" position="bottom">
            <van-picker
                :columns="colorOptions"
                @confirm="onColorConfirm"
                @cancel="showColorPicker = false"
            />
        </van-popup>
        
        <!-- 品种选择器 -->
        <van-popup v-model:show="showBreedPicker" position="bottom">
            <van-picker
                :columns="breedOptions"
                @confirm="onBreedConfirm"
                @cancel="showBreedPicker = false"
            />
        </van-popup>
        
        <!-- 年龄选择器 -->
        <van-popup v-model:show="showAgePicker" position="bottom">
            <van-picker
                :columns="ageOptions"
                @confirm="onAgeConfirm"
                @cancel="showAgePicker = false"
            />
        </van-popup>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Toast } from 'vant'
import { addPet } from '@/api/index'
import { useUserStore } from '@/stores/user'

// 导入具体的 Toast 方法
import { showLoadingToast, showSuccessToast, showFailToast, showConfirmDialog } from 'vant'

const router = useRouter()
const userStore = useUserStore()


const form = reactive({
    pet_name: '',
    pet_type: '',
    pet_gender: '',
    pet_breed: '',
    pet_age: '',
    pet_color: '',
    pet_image: '',
    user_id: '' 
})

// 文件列表
const fileList = ref([])
const selectedFile = ref(null) // 用于存储选中的文件

// 加载状态
const loading = ref(false)

// 选择器显示状态
const showGenderPicker = ref(false)
const showColorPicker = ref(false)
const showBreedPicker = ref(false)
const showAgePicker = ref(false)

// 选项数据
const genderOptions = [
    { text: '公', value: '公' },
    { text: '母', value: '母' },
    { text: '未知', value: '未知' }
]

const colorOptions = [
    { text: '白色', value: '白色' },
    { text: '黑色', value: '黑色' },
    { text: '棕色', value: '棕色' },
    { text: '灰色', value: '灰色' },
    { text: '橙色', value: '橙色' },
    { text: '黄色', value: '黄色' },
    { text: '花色', value: '花色' }
]

const breedOptions = [
    { text: '金毛', value: '金毛' },
    { text: '拉布拉多', value: '拉布拉多' },
    { text: '哈士奇', value: '哈士奇' },
    { text: '柯基', value: '柯基' },
    { text: '泰迪', value: '泰迪' },
    { text: '比熊', value: '比熊' },
    { text: '英短', value: '英短' },
    { text: '美短', value: '美短' },
    { text: '田园猫', value: '田园猫' },
    { text: '其他', value: '其他' }
]

const ageOptions = [
    { text: '1个月以下', value: '1个月以下' },
    { text: '1-3个月', value: '1-3个月' },
    { text: '3-6个月', value: '3-6个月' },
    { text: '6-12个月', value: '6-12个月' },
    { text: '1-2岁', value: '1-2岁' },
    { text: '2-4岁', value: '2-4岁' },
    { text: '4-6岁', value: '4-6岁' },
    { text: '6-8岁', value: '6-8岁' },
    { text: '8岁以上', value: '8岁以上' }
]

// 方法
const handleBack = () => {
    router.back()
}

const afterRead = async (file) => {
    // 保存文件信息，但不立即上传
    // 实际上传将在提交表单时与宠物信息一起上传
    selectedFile.value = file.file;
}

const beforeDelete = () => {
    selectedFile.value = null;
    form.pet_image = '';
    return true;
}

const onGenderConfirm = (value) => {
    form.pet_gender = value.selectedValues[0];
    showGenderPicker.value = false;
}

const onColorConfirm = (value) => {
    form.pet_color = value.selectedValues[0];
    showColorPicker.value = false;
}

const onBreedConfirm = (value) => {
    form.pet_breed = value.selectedValues[0];
    showBreedPicker.value = false;
}

const onAgeConfirm = (value) => {
    form.pet_age = value.selectedValues[0];
    showAgePicker.value = false;
}

const handleSubmit = async () => {
    // 检查用户是否已登录
    console.log('提交时的token值:', userStore.token);
    if (!userStore.token) {
        // 用户未登录，提示先登录
        try {
            await showConfirmDialog({
                title: '提示',
                message: '添加宠物需要先登录，是否前往登录？',
                confirmButtonText: '去登录',
                cancelButtonText: '取消'
            });
            
            // 点击确认按钮后跳转到登录页
            router.push('/user/login');
        } catch (error) {
            // 用户点击了取消按钮
            console.log('用户取消操作');
        }
        return;
    }

    // 设置用户ID
    form.user_id = userStore.uid || "";

    loading.value = true;
    try {
        // 创建 FormData 对象用于上传图片和宠物信息
        const formData = new FormData();
        
        // 添加宠物信息字段 (与后端 PetDTO 字段对应)
        formData.append('petName', form.pet_name);
        // 将字符串类型转换为后端需要的整数类型
        formData.append('petType', form.pet_type === '猫猫' ? 0 : 1);
        // 将字符串类型转换为后端需要的整数类型
        const genderMap = {'公': 0, '母': 1, '未知': 2};
        formData.append('petGender', genderMap[form.pet_gender] !== undefined ? genderMap[form.pet_gender] : 2);
        formData.append('petColor', form.pet_color);
        formData.append('petBreed', form.pet_breed);
        // 将字符串类型转换为后端需要的整数类型
        const ageMap = {
            '1个月以下': 0, 
            '1-3个月': 1, 
            '3-6个月': 2, 
            '6-12个月': 3, 
            '1-2岁': 4, 
            '2-4岁': 5, 
            '4-6岁': 6, 
            '6-8岁': 7, 
            '8岁以上': 8
        };
        formData.append('petAge', ageMap[form.pet_age] !== undefined ? ageMap[form.pet_age] : 0);
        formData.append('userId', form.user_id);
        
        // 如果有选中的图片文件，则添加到 FormData
        if (selectedFile.value) {
            formData.append('image', selectedFile.value);
        }
        
        // 调用后端接口添加宠物（包含图片）
        const response = await addPet(formData);
        
        showSuccessToast('添加成功');
        // 添加成功后返回首页
        router.push('/recommend');
    } catch (error) {
        // 更详细的错误日志记录
        console.error('添加宠物失败:', error);
        console.error('当前token:', userStore.token);
        showFailToast('添加失败：' + (error.message || '请稍后重试'));
    } finally {
        loading.value = false;
    }
};
</script>

<style lang="scss" scoped>
.add-pet-page {
    min-height: 100vh;
    background-color: #FFD833;
    max-width: 500px;  /* 限制最大宽度 */
    margin: 0 auto;    /* 居中显示 */
    
    ::v-deep(.van-nav-bar) {
        background-color: #FFD833;
        
        .van-nav-bar__arrow {
            color: #333;
        }
        
        .van-nav-bar__text {
            color: #333;
        }
    }
    
    .page-content {
        padding: 16px;
    }
    
    .avatar-section {
        background: white;
        border-radius: 8px;
        padding: 16px;
        margin-bottom: 16px;
        text-align: center;
        
        .section-title {
            font-size: 16px;
            color: #333;
            margin-bottom: 12px;
            font-weight: 500;
        }
        
        .uploader-wrapper {
            display: flex;
            justify-content: center;
            
            .custom-upload-area {
                width: 80px;
                height: 80px;
                border-radius: 50%;
                overflow: hidden;
                position: relative;
                border: 2px dashed #ddd;
                display: flex;
                align-items: center;
                justify-content: center;
                cursor: pointer;
                transition: all 0.3s ease;
                
                &:hover {
                    border-color: #FFD833;
                    transform: scale(1.05);
                }
                
                .default-avatar {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
                
                &::after {
                    content: '+';
                    position: absolute;
                    bottom: 3px;
                    right: 3px;
                    width: 16px;
                    height: 16px;
                    background: #FFD833;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: #333;
                    font-weight: bold;
                    font-size: 12px;
                }
            }
        }
    }

    .pet-form {
        background: white;
        border-radius: 8px;
        padding: 20px;
        
        ::v-deep(.van-cell) {
            padding: 20px 0;
            
            &:not(.no-border) {
                border-bottom: 1px solid #000;
            }
            
            &.no-border {
                padding-bottom: 10px;
            }
            
            &:last-child {
                border-bottom: none;
            }
        }
        
        ::v-deep(.van-cell-group) {
            &:not(.no-border) {
                border-bottom: 1px solid #000;
            }
        }
        
        ::v-deep(.van-field__label) {
            font-size: 16px;
        }
        
        .pet-type-radio {
            ::v-deep(.van-radio__icon--checked) {
                .van-icon {
                    background-color: #FFD833;
                    border-color: #FFD833;
                }
            }
            
            ::v-deep(.van-radio__label--checked) {
                color: #FFD833;
            }
        }
        
        .submit-btn {
            margin-top: 40px;
            
            // 修改按钮背景色为 #FFD833
            ::v-deep(.van-button--primary) {
                background: #FFD833;
                border-color: #FFD833;
                color: #333; // 设置文字颜色，确保可读性
            }
        }
    }
}    </style>